package com.y2.authprj.mvc.controller.auth;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gdglc.spring.annotations.AuthValidate;
import com.gdglc.spring.biz.auth.FunctionauthorityBiz;
import com.y2.authprj.bean.auth.model.FunctionauthorityInfo;
import com.y2.authprj.bean.auth.model.iDs;
import com.y2.authprj.utils.DateSqlUtil;

@Controller
@RequestMapping("/functionauthority")
public class FunctionauthorityController {

	@Resource(name="functionBiz")
	private FunctionauthorityBiz biz;
	
	@RequestMapping("/show")
	public String show(Model model){
		
		List<FunctionauthorityInfo> functions = biz.findAll();
		model.addAttribute("functions", functions);
		model.addAttribute("infos",functions);
		return "auth/functionauthority";
	}
	
	/**
	 * 根据param决定返回的model
	 * @param param
	 * @param model
	 * @return
	 */
	public String showAll(String param,Model model){
		if(param.equals("add")){
			List<FunctionauthorityInfo> functions = biz.findAll();
			model.addAttribute("functions", functions);
			model.addAttribute("infos",functions);
			model.addAttribute("message", "提示：添加成功！");
		}else if(param.equals("edit")){
			List<FunctionauthorityInfo> functions = biz.findAll();
			model.addAttribute("functions", functions);
			model.addAttribute("infos",functions);
			model.addAttribute("message", "提示：修改成功！");
		}else if(param.equals("show")){
			List<FunctionauthorityInfo> functions = biz.findAll();
			model.addAttribute("functions", functions);
		}else if(param.equals("delete")){
			List<FunctionauthorityInfo> functions = biz.findAll();
			model.addAttribute("functions", functions);
			model.addAttribute("infos",functions);
			model.addAttribute("message","提示：删除成功！");
		}
		return "auth/functionauthority";
	}
	
	public String showAll(Model model){
		List<FunctionauthorityInfo> functions = biz.findAll();
		model.addAttribute("functions", functions);
		model.addAttribute("functions",functions);
		return "auth/functionauthority";
	}
	
	@AuthValidate("新增权限")
	@RequestMapping("/add")
	public String add(FunctionauthorityInfo info,boolean isParent,Model model){
		FunctionauthorityInfo f = new FunctionauthorityInfo();
		FunctionauthorityInfo parentInfo = biz.findById(String.valueOf(info.getParentId()));
		int num = (int)(Math.random()*1000000);
		f.setFunctionauthorityId(num);
		f.setName(info.getName());
		f.setKeyValue(num+"_"+info.getKeyValue());
		f.setParentId(info.getParentId());
		f.setIsgroup(2);
		f.setCreateTime(java.sql.Date.valueOf(DateSqlUtil.formate(new Date())));
		f.setDeleteFlag(1);
		if(isParent==false){
			parentInfo.setIsgroup(1);
			biz.updateIsgroup(parentInfo);
		}
		
		int i = biz.add(f);
		if(i>0){
			return showAll("add",model);
			
		}else{
			return null;
		}
	}
	
	private static String jsonString(String s){
        char[] temp = s.toCharArray();       
        int n = temp.length;
        for(int i =0;i<n;i++){
            if(temp[i]==':'&&temp[i+1]=='"'){
                    for(int j =i+2;j<n;j++){
                        if(temp[j]=='"'){
                            if(temp[j+1]!=',' &&  temp[j+1]!='}'){
                                temp[j]='”';
                            }else if(temp[j+1]==',' ||  temp[j+1]=='}'){
                                break ;
                            }
                        }
                    }   
            }
        }       
        return new String(temp);
    }
	
	@AuthValidate("删除权限")
	@RequestMapping("/delete")
	public String delete(Integer id,String[] ids,Model model){
		//查询是否是分组 1（分组）、2（子节点）
		if(ids!=null){
			List<String> funcIds = new ArrayList<String>();
			for(int i = 0;i<ids.length;i++){			
				int begin = ids[i].indexOf(':')+2;
				int end = ids[i].lastIndexOf('"');
				System.out.println();
				funcIds.add(ids[i].substring(begin, end));
				i=i+3;
			}
			for(int t=0;t<funcIds.size();t++){
				FunctionauthorityInfo fun = biz.findById(funcIds.get(t).toString());
				if(fun!=null){
					int idNo = biz.getIsGroup(Integer.parseInt(funcIds.get(t).toString()));
					
					if(idNo == 1){
						//删除父节点
						biz.deleteParentById(Integer.parseInt(funcIds.get(t).toString()));
						//记录父节点Id
						int parentId=Integer.parseInt(funcIds.get(t).toString());
						
						List<FunctionauthorityInfo> f = new ArrayList<FunctionauthorityInfo>();
						List<FunctionauthorityInfo> f2 = biz.getChileByRoot(parentId);
						boolean flag = true;
						while(flag){
							if(f.size()==0){
								for(int i = 0;i<f2.size();i++){
									f.add(f2.get(i));
								}
							}
							
							List<FunctionauthorityInfo> f3 = new ArrayList<FunctionauthorityInfo>();
							
							for(int a = 0; a<f.size();a++){
								List<FunctionauthorityInfo> f4 = biz.getChileByRoot(f.get(a).getFunctionauthorityId());
								if(f4.size()!=0){
									boolean isExist = false;
									for(int j = 0;j<f4.size();j++){
										//在f集合总不存在的值才能添加
										for(int l=0;l<f.size();l++){
											if(f.get(l).getFunctionauthorityId()==f4.get(j).getFunctionauthorityId()){
												isExist = true;
											}
										}
										if(!isExist){
											f3.add(f4.get(j));
										}
									}
								}
							}
							
							if(f3.size()!=0){
								boolean isExist = false;
								for(int k = 0;k<f3.size();k++){
									for(int i=0;i<f.size();i++){
										if(f.get(i).getFunctionauthorityId()==f3.get(k).getFunctionauthorityId()){
											isExist = true;
										}
									}
									if(!isExist){
										f.add(f3.get(k));
									}
								}
							}else{
								for(int g=0;g<f.size();g++){
									biz.deleteParentById(f.get(g).getFunctionauthorityId());
								}
								flag = false;
							}
						}
										
					}else{
						biz.deleteParentById(Integer.parseInt(funcIds.get(t).toString()));
					}
				}
			}
		}else{
			int idNo = biz.getIsGroup(id);
			
			if(idNo == 1){
				//删除父节点
				biz.deleteParentById(id);
				//记录父节点Id
				int parentId=id;
				
				List<FunctionauthorityInfo> f = new ArrayList<FunctionauthorityInfo>();
				List<FunctionauthorityInfo> f2 = biz.getChileByRoot(parentId);
				boolean flag = true;
				while(flag){
					if(f.size()==0){
						for(int i = 0;i<f2.size();i++){
							f.add(f2.get(i));
						}
					}
					
					List<FunctionauthorityInfo> f3 = new ArrayList<FunctionauthorityInfo>();
					
					for(int a = 0; a<f.size();a++){
						List<FunctionauthorityInfo> f4 = biz.getChileByRoot(f.get(a).getFunctionauthorityId());
						if(f4.size()!=0){
							boolean isExist = false;
							for(int j = 0;j<f4.size();j++){
								//在f集合总不存在的值才能添加
								for(int l=0;l<f.size();l++){
									if(f.get(l).getFunctionauthorityId()==f4.get(j).getFunctionauthorityId()){
										isExist = true;
									}
								}
								if(!isExist){
									f3.add(f4.get(j));
								}
							}
						}
					}
					
					if(f3.size()!=0){
						boolean isExist = false;
						for(int k = 0;k<f3.size();k++){
							for(int i=0;i<f.size();i++){
								if(f.get(i).getFunctionauthorityId()==f3.get(k).getFunctionauthorityId()){
									isExist = true;
								}
							}
							if(!isExist){
								f.add(f3.get(k));
							}
						}
					}else{
						for(int g=0;g<f.size();g++){
							biz.deleteParentById(f.get(g).getFunctionauthorityId());
						}
						flag = false;
					}
				}
								
			}else{
				biz.deleteParentById(id);
			}
		}
		return "redirect:/functionauthority/show";
	}
	
	@AuthValidate("修改权限")
	@RequestMapping("/edit")
	public String edit(FunctionauthorityInfo info,Model model) throws Exception{
		List<FunctionauthorityInfo> infos = biz.findByParentId(String.valueOf(info.getParentId()));
		List<FunctionauthorityInfo> functions = biz.findAll();
		for(FunctionauthorityInfo f:infos){
			if(info.equals(f.getName())){
				throw new Exception("修改失败，同组下非删除同名");
			}
		}
		
		FunctionauthorityInfo function = new FunctionauthorityInfo();
		function.setFunctionauthorityId(info.getFunctionauthorityId());
		function.setName(info.getName());
		function.setKeyValue(info.getKeyValue());
		function.setCreateTime(java.sql.Date.valueOf(DateSqlUtil.formate(new Date())));
		biz.update(function);
		
		return showAll("edit",model);
	}
	
	/**
	 * 首先判断isParent是否为父节点如果是false查询当前节点信息
	 * 如果为true则返回当前节点以及子节点的信息
	 * @param info
	 * @param isParent
	 * @param model
	 * @return
	 */
	@RequestMapping("/find")
	public String find(FunctionauthorityInfo info,boolean isParent,Model model){
		if(isParent){
			FunctionauthorityInfo function = biz.findById(String.valueOf(info.getFunctionauthorityId()));
			List<FunctionauthorityInfo> functions = biz.findByParentId(String.valueOf(info.getFunctionauthorityId()));
			functions.add(0, function);
			model.addAttribute("infos",functions);
		}else{
			FunctionauthorityInfo function = biz.findById(String.valueOf(info.getFunctionauthorityId()));
			List<FunctionauthorityInfo> functions = new ArrayList<FunctionauthorityInfo>();
			functions.add(function);
			model.addAttribute("infos",functions);
		}
		
		return showAll(model);
	}
}
